<template>
  <div class="container">
    <section class="search-container">
      <search-temp @search="initList"></search-temp>
    </section>
    <a-table
      :columns="columns"
      :rowKey="record => record._id"
      :dataSource="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :scroll="{ x: 1300 }"
    >
      <template slot="handler" slot-scope="row">
        <a-button v-show="row.result == UpgradeResult.ERROR" type="primary" size="small" ghost @click="handlerDownload(row.httpPath)">下载</a-button>
      </template>
      <template slot="createTime" slot-scope="createTime">{{ createTime | fmtDate }}</template>
      <template slot="osType" slot-scope="osType">{{ OsType2Val[osType] }}</template>
      <template slot="driverType" slot-scope="driverType">{{ DriverType2Val[driverType] }}</template>
      <template slot="cpuBits" slot-scope="cpuBits">{{ CpuBits2Val[cpuBits] }}</template>
      <template slot="result" slot-scope="result">{{ Result2Val[result] }}</template>
    </a-table>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { SearchTemp } from "./components";
import { log_pages, log_count } from "@/api/log";
import { columns } from "./logs";
import { OsType2Val, DriverType2Val, CpuBits2Val, Result2Val, SortBy2Val } from "@/common/Enum2Val";
import { UpgradeResult } from "@/utils/VEnum";
import { PaginationMixin } from "@/mixins";
import { fmtDate } from "@/filters";

@Component({
  name: "DriveTable",
  components: { SearchTemp },
  filters: { fmtDate },
  data() {
    return {
      OsType2Val,
      DriverType2Val,
      CpuBits2Val,
      Result2Val,
      UpgradeResult
    };
  }
})
export default class Logs extends PaginationMixin {
  private loading: boolean = false;
  private data: any[] = [];
  private columns: any[] = columns;

  handlerDownload(path: string) {
    window.location.href = path;
  }

  handleTableChange(pagination: any, filters: any, sorter: any) {
    const { order } = sorter;
    const search: any = {};
    if (SortBy2Val[order]) search.sortBy = SortBy2Val[order]
    const pager = { ...this.pagination };
    pager.current = pagination.current;
    this.pagination = pager;
    this.initList(search);
  }

  async initList(search?: any) {
    const paper: any = this.pagination;
    const current: number = paper.current;
    let query: any = {
      page: current,
      count: this.pageSize
    };
    if (search) query = { ...query, ...search };
    try {
      this.loading = true;
      const [{ data: page }, { data: count }] = await Promise.all([
        log_pages(query),
        log_count(query)
      ]);
      this.loading = false;
      this.pagination.total = count.item;
      this.data = page.item;
    } catch (error) {
      this.loading = false;
    }
  }

  created() {
    this.initList();
  }
}
</script>
<style lang="less" scoped>
.search-container {
  padding-bottom: 10px;
}
</style>
